<!--
*  2021-03-15
*  成品盘点
-->
<template>
  <div id="app" class="store-edit">
    <!-- 头部导航 -->
    <van-nav-bar
      title="成品盘点详情"
      ref="header"
      left-arrow
      left-text="返回"
      @click-left="onClickLeft"
    >
    </van-nav-bar>
    <better-scroll
      class="public-scroll"
      :data="tableData"
      :totalPage="totalPage"
    >
      <van-cell-group>
        <van-cell title="品名">
          <template>
            <van-search
              v-model="printRow.designNo"
              type="text"
              placeholder="输入名称"
              clearable
              ref="fieldInput"
              :disabled="printRow.id != ''"
              @search="onSearch"
            ></van-search>
          </template>
        </van-cell>
        <van-cell title="色号">
          <template>
            <van-field
              v-model="printRow.color"
              placeholder="请输入"
              clearable
              :disabled="printRow.id != ''"
            ></van-field>
          </template>
        </van-cell>
        <van-cell title="缸号">
          <template>
            <van-field
              v-model="printRow.vatNo"
              placeholder="请输入"
              clearable
              :disabled="printRow.id != ''"
            ></van-field>
          </template>
        </van-cell>
        <van-cell title="库存">
          <template>
            <van-field
              v-model="printRow.num"
              placeholder="请输入"
              clearable
              type="tel"
              :disabled="printRow.id != ''"
            ></van-field>
          </template>
        </van-cell>
       
        <van-cell title="重量">
          <template>
            <van-field
              v-model="printRow.weight"
              placeholder="请输入"
              clearable
              type="tel"
              :disabled="printRow.id != ''"
            ></van-field>
          </template>
        </van-cell>
        <van-cell title="长度">
          <template>
            <van-field
              v-model="printRow.length"
              placeholder="请输入"
              clearable
              type="tel"
              :disabled="printRow.id != ''"
            ></van-field>
          </template>
        </van-cell>
         <van-cell
          title="区域"
          is-link
          :value="printRow.area"
          @click="showPicker = true"
        ></van-cell>
        <van-cell title="打印数量">
          <template>
            <van-field
              v-model="printCount"
              placeholder="请输入"
              clearable
              type="tel"
              @focus="onClickFocus"
            ></van-field>
          </template>
        </van-cell>
      </van-cell-group>
    </better-scroll>

    <van-cell-group class="store-edit__scroll store-edit__btn">
      <van-button
        block
        type="info"
        class="bgColor"
        @click="onClickConfirm"
        v-if="printRow.id === ''"
        >保 存</van-button
      >
      <van-button
        block
        type="info"
        class="bgColor"
        @click="onClickConfirm"
        v-else
        >打 印</van-button
      >
    </van-cell-group>

    <!-- 区域 -->
    <van-popup v-model="showPicker" position="bottom" get-container="body">
      <van-picker
        show-toolbar
        :columns="areaColumns"
        @confirm="onConfirm"
        @cancel="showPicker = false"
      />
    </van-popup>

    <van-popup v-model="showDesignNo" position="bottom" get-container="body">
      <van-picker
        show-toolbar
        value-key="designNo"
        :columns="columns"
        @confirm="onConfirmDesignNo"
        @cancel="showDesignNo = false"
      />
    </van-popup>
  </div>
</template>

<script>
import { openWin } from "@/utils/index";
import { getClothNoteAreas, getProductFilterTopNo, getProductStoreCheck } from "@/api/product";
import { getMacAddress } from "@/utils/auth";
import dayjs from "dayjs";

export default {
  name: "productStoreEdit",
  data() {
    return {
      tableData: [],
      totalPage: 1,
      showPicker: false,
      columns: [],
      areaColumns: [],
      printCount: 1,
      printRow: {
        id: "",
        designId: "",
        vatNo: "无",
        area: "",
        designNo: "",
        color: "",
        num: "",
        weight: "",
        length: "",
        optName: "",
      },
      printStatus: false,
      showDesignNo: false,
    };
  },
  watch: {
    designNo(val) {
      if (val) {
        let index = this.columns.findIndex((item) => item.designNo == val);
        if (index != -1) {
          this.printRow.designId = this.columns[index].designId;
        } else {
          this.printRow.designId = "";
        }
      }
    },
  },
  created() {
    const that = this;
    if (process.env.NODE_ENV === "production") {
      this.$nextTick(() => {
        that.initFn(that);
      });
    } else {
      window.apiready = function () {
        that.initFn(that);
      };
    }
  },
  methods: {
    //初始化
    initFn(that) {
      if (JSON.stringify(window.api.pageParam) != "{}") {
        that.printRow = window.api.pageParam;
      }
      that.onGetTableList();
      if (getMacAddress()) {
        that.isEnabledBluetooth();
      } else {
        that.$toast.fail("如需打印，请退出登录选择打印机");
      }
      window.api.addEventListener({
        name:'viewdisappear'
      }, function() {
        window.api.closeWin();
      });
    },
    // 返回
    onClickLeft() {
      openWin("product-store");
    },
    // 配置列表
    onGetTableList() {
      getClothNoteAreas({}, (res) => {
        this.printRow.area = this.printRow.area ? this.printRow.area : res[0];
        this.areaColumns = res;
      });
    },
    // 获取编号
    onSearch() {
      this.showDesignNo = false;
      this.columns = [];
      getProductFilterTopNo(
        {
          designNo: this.printRow.designNo,
        },
        (res) => {
          if (res.length == 0) {
            this.$toast.fail("筛选无数据");
          } else {
            res.forEach((item) => {
              let params = {};
              params.designNo = item.topNo;
              params.designId = item.designId;
              this.columns.push(params);
            });
            this.showDesignNo = true;
          }
        }
      );
    },
    // 确认品名
    onConfirmDesignNo(val) {
      this.printRow.designNo = val.designNo;
      this.printRow.designId = val.designId;
      this.printRow.color = val.colorNo;
      this.showDesignNo = false;
    },
    // 区域选择
    onConfirm(value) {
      if (this.printRow.id === "") {
        this.printRow.area = value;
        this.showPicker = false;
      }
    },
    // 打印获取焦点
    onClickFocus() {
      this.printCount = "";
    },
    // 保存
    onClickConfirm() {
      const that = this;
      if (this.printRow.id) {
        that.printCount = that.printCount == "" ? 1 : that.printCount;
        that.$toast({
          type: "success",
          message: "打印中",
          duration: 1000,
          onClose: () => {
            that.onClickPrint();
          },
        });
      } else {
        getProductStoreCheck(this.printRow, (res) => {
          that.printCount = that.printCount == "" ? 1 : that.printCount;
          this.printRow.id = res.id;
          this.printRow.optName = res.optName;
          that.$toast({
            type: "success",
            message: "打印中",
            duration: 1000,
            onClose: () => {
              that.onClickPrint();
            },
          });
        });
      }
    },
    // 判断蓝牙是否打开
    isEnabledBluetooth() {
      const that = this;
      window.api
        .require("cxgBluetoothBase")
        .isEnabledBluetooth({}, (ret, err) => {
          if (!err) {
            if (ret.state) {
              // 已打开
              that.connectBleByMacAddress();
            } else {
              that.openBluetooth();
            }
          } else {
            that.$toast.fail("code: " + err.code + " msg: " + err.msg);
          }
        });
    },
    // 打开蓝牙
    openBluetooth() {
      const that = this;
      window.api
        .require("cxgBluetoothBase")
        .openBluetooth({}, function (ret, err) {
          if (!err) {
            if (ret.state) {
              // 已打开
              that.connectBleByMacAddress();
            }
          } else {
            that.listenBluetoothStatus();
          }
        });
    },
    // 监听蓝牙连接状态
    listenBluetoothStatus() {
      const that = this;
      window.api
        .require("cxgBluetoothBase")
        .listenBluetoothStatus({}, function (ret, err) {
          if (!err) {
            if (ret.status === "STATE_ON") {
              that.connectBleByMacAddress();
            }
          } else {
            that.$toast.fail("code: " + err.code + " msg: " + err.msg);
          }
        });
    },
    // 查询打印机连接状态
    getConnectState() {
      const that = this;
      that.$toast({
        message: "正在打印",
        type: "loading",
        duration: 20000,
      });
      var obj = window.api.require("xGprinterPlus");
      var ret = obj.getConnectState();
      if (ret.status) {
        let result = false;
        ret.state.forEach((bool) => {
          if (bool) {
            result = bool;
          }
        });
        if (result) {
          // 已连接
          that.$toast.clear();
          if (that.printStatus) {
            that.printLabel();
          }
        } else {
          // 未连接
          that.$toast({
            type: "fail",
            message: "未连接, 请等待",
            duration: 1500,
            onClose: () => {
              that.connectBleByMacAddress();
            },
          });
        }
      } else {
        // 未连接
        that.$toast({
          type: "fail",
          message: "未连接, 请等待",
          duration: 1500,
          onClose: () => {
            that.connectBleByMacAddress();
          },
        });
      }
    },
    // 连接蓝牙
    connectBleByMacAddress(status) {
      const that = this;
      if (that.printStatus) {
        that.$toast({
          message: "初始化打印机",
          type: "loading",
          duration: 20000,
        });
      }
      var demo = window.api.require("xGprinterPlus");
      demo.connectBleByMacAddress(
        {
          macAddress: getMacAddress() ? getMacAddress().address : "",
        },
        function (ret, err) {
          if (ret.status) {
            if (ret.message === "已连接") {
              that.connectionStatus = true;
              if (that.printStatus) {
                that.$toast({
                  type: "success",
                  message: "连接成功",
                  duration: 1500,
                  onClose: () => {
                    that.printLabel();
                  },
                });
              }
              if (status) {
                that.onClickAddStore();
              }
            } else if (ret.message === "连接失败") {
              that.connectionStatus = false;
              that.$toast({
                type: "fail",
                message: "初始化失败",
                duration: 1500,
              });
            } else {
              that.connectionStatus = false;
            }
          } else {
            that.$toast({
              type: "fail",
              message: err.msg,
              duration: 1500,
            });
          }
        }
      );
    },
    // 打印数据
    printLabel() {
      const that = this;
      var obj = window.api.require("xGprinterPlus");
      obj.printLabel(
        {
          rows: [
            {
              lineType: "size",
              width: 50,
              height: 70,
            },
            {
              lineType: "gap",
              data: 3,
            },
            {
              lineType: "cls",
            },
            {
              // 图片单元格竖线
              lineType: "bar",
              x: 25 + 130,
              y: 0,
              width: 2,
              height: 136,
            },
            {
              //绘制图片
              lineType: "image",
              x: 25 + 8,
              y: 8,
              data: "widget://image/huibo_logo.png",
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 8,
              y: 10,
              rotation: 0,
              xscal: 1,
              yscal: 1,
              data: "艺多染整",
            },
            {
              // 横线
              lineType: "bar",
              x: 25 + 4,
              y: 186,
              width: 130,
              height: 2,
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 4,
              y: 136 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: dayjs().format("YYYY-MM-DD"),
            },
            {
              // 横线
              lineType: "bar",
              x: 25,
              y: 236,
              width: 608,
              height: 2,
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 8,
              y: 236,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: "成品盘库码（" + that.printRow.id.toString() + "）",
            },

            {
              lineType: "qrcode", // 绘制qrcode
              x: 25 + 150 + 2,
              y: 10,
              level: "L", //L|M|H|Q
              cellwith: 9,
              rotation: 0, // 0|90|180|270
              data: "15," + that.printRow.id.toString(),
            },

            {
              //绘制文本
              lineType: "text",
              x: 25 + 4,
              y: 286 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: "品名: " + that.printRow.designNo,
            },
            {
              // 横线
              lineType: "bar",
              x: 25,
              y: 286,
              width: 608,
              height: 2,
            },

            {
              //绘制文本
              lineType: "text",
              x: 25 + 4,
              y: 336 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: "色号: " + that.printRow.color,
            },
            {
              // 横线
              lineType: "bar",
              x: 25,
              y: 336,
              width: 608,
              height: 2,
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 4,
              y: 386 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: "盘后库存: " + that.printRow.num,
            },
            {
              // 横线
              lineType: "bar",
              x: 25,
              y: 386,
              width: 608,
              height: 2,
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 4,
              y: 436 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: "区域: " + that.printRow.area,
            },
            {
              // 横线
              lineType: "bar",
              x: 25,
              y: 436,
              width: 608,
              height: 2,
            },
            {
              //绘制文本
              lineType: "text",
              x: 25 + 4,
              y: 486 + 2,
              rotation: 0,
              xscal: 1,
              yscal: 2,
              data: "操作人: " + that.printRow.optName,
            },
            {
              // 横线
              lineType: "bar",
              x: 25,
              y: 486,
              width: 608,
              height: 2,
            },
          ],
        },
        function (ret, err) {
          if (ret.status) {
            if (that.printCount <= 0) {
              that.$toast.success("打印成功");
            } else {
              that.onClickPrint();
            }
          } else {
            that.$toast({
              type: "fail",
              message: err.code + err.msg,
              duration: 1500,
              onClose: () => {
                that.connectBleByMacAddress();
              },
            });
          }
        }
      );
    },
    onClickPrint() {
      const that = this;
      --this.printCount;
      this.printStatus = true;
      if (!getMacAddress()) {
        this.$toast.fail("如需打印，请退出登录选择打印机");
        return false;
      }
      this.$toast({
        type: "success",
        message: "打印中",
        duration: 1000,
        onClose: () => {
          that.getConnectState();
        },
      });
    },
  },
};
</script>

<style lang="scss">
.store-edit {
  display: flex;
  flex-direction: column;
  height: 100%;
  .van-cell {
    .van-cell__title {
      flex: 1;
    }
    .van-cell__value {
      flex: 0 0 80%;
      text-align: right;
      .van-field__control {
        text-align: right;
      }
      .van-cell {
        padding: 0;
        .van-cell__value {
          flex: 1;
        }
      }
    }
  }

  .van-search {
    padding: 0;
    z-index: 1;
  }
  .store-edit__scroll {
    // flex: 1;
    overflow: hidden;
  }
  .store-edit__btn {
    padding: 16px;
    &.van-hairline--top-bottom::after,
    .van-hairline-unset--top-bottom::after {
      border-width: 0;
    }
  }
}
</style>
